package com.vonchange.utils.res.compressor;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mozilla.javascript.EvaluatorException;

import com.vonchange.utils.file.FileUtils;
import com.vonchange.utils.res.bean.ResErrorReport;
import com.yahoo.platform.yui.compressor.CssCompressor;
import com.yahoo.platform.yui.compressor.JavaScriptCompressor;

public class TResCompressorUtils {
	static int linebreakpos = -1;
	static boolean munge = true;
	static boolean verbose = false;
	static boolean preserveAllSemiColons = false;
	static boolean disableOptimizations = false;
	static String charset = "UTF-8";
	private static Log logger = LogFactory.getLog(TResCompressorUtils.class);

	public static String jsCompressorByFile(File jsFile) {
		String result = null;
		if(!jsFile.exists()){
			return null;
		}
		try {
			result = TResCompressorUtils.jsCompressor(FileUtils.readFileToString(jsFile, charset));
		} catch (EvaluatorException | IOException e) {
			logger.error(jsFile.getName());
			e.printStackTrace();
		}
		return result;
	}

	public static String jsCompressor(String jsOrgStr) throws EvaluatorException, IOException {
		Reader in = null;
		Writer out = null;
		String jsStr = null;
		in = new StringReader(jsOrgStr);
		JavaScriptCompressor compressor;
		compressor = new JavaScriptCompressor(in, new ResErrorReport());
		in.close();
		in = null;
		out = new StringWriter();
		compressor.compress(out, linebreakpos, munge, verbose, preserveAllSemiColons, disableOptimizations);
		out.flush();
		jsStr = out.toString();
		out.close();
		out=null;
		return jsStr;
	}

	public static String cssCompressor(File cssFile) {
		String result = null;
		if(!cssFile.exists()){
			return null;
		}
		try {
			result = TResCompressorUtils.cssCompressor(FileUtils.readFileToString(cssFile, charset));
		} catch (IOException e) {
			logger.error(cssFile.getName());
			e.printStackTrace();
		}
		return result;
	}

	public static String cssCompressor(String cssOrgStr) throws IOException {
		Reader in = null;
		Writer out = null;
		String jsStr = null;
		in = new StringReader(cssOrgStr);
		CssCompressor compressor;
		compressor = new CssCompressor(in);
		in.close();
		in = null;
		out = new StringWriter();
		compressor.compress(out, linebreakpos);
		out.flush();
		jsStr = out.toString();
		out.close();
		out=null;
		return jsStr;
	}

}
